//
//  DDSearchViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/28.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDSearchViewController.h"
#import "DDGoodsManager.h"
#import "DDGoodsListViewController.h"
#import "KKFileManager.h"
#import "DDHomeManager.h"
#import "DDHotSearchSet.h"

@interface DDSearchViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (strong, nonatomic) UITableView *historyTable;
@property (strong, nonatomic) UITextField *searchTxf;
@property (strong, nonatomic) NSArray *historySearchAry;
@property (strong, nonatomic) DDHomeManager *manager;
@property (strong, nonatomic) DDHotSearchSet *hotSet;
@property (strong, nonatomic) UIScrollView *searchScrollView;
@end

@implementation DDSearchViewController
- (void)gotoBack
{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *fileName = [KKFileManager createFileWithName:@"SearchHistory"];
    NSArray *searchAry = [NSArray arrayWithContentsOfFile:fileName];
    self.historySearchAry = searchAry;
    [self fetchHotSearch];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDHomeManager new];
    [self setLeftBarItem];
    [self layoutSearchView];
}
- (void)layoutSearchView
{
    self.view.backgroundColor = RGBColor(237, 237, 237);
    
    UIView *searchBackView = [[UIView alloc]initWithFrame:CGRectMake(70, 27, ScreenWidth-60, 30)];
    searchBackView.backgroundColor = [UIColor whiteColor];
    searchBackView.layer.cornerRadius = 3.0;
    self.navigationItem.titleView = searchBackView;
    
    UIView *searchBarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    searchBarView.backgroundColor = RGBColor(237, 237, 237);
    searchBarView.layer.cornerRadius = 3.0;
    [searchBackView addSubview:searchBarView];
    [searchBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBackView);
        make.left.equalTo(searchBackView).offset(0);
        make.right.equalTo(searchBackView).offset(-80);
        make.height.equalTo(@30);
    }];
    
    UIImageView *icon = [[UIImageView alloc]initWithImage:LoadImage(@"home_sousuo")];
    [searchBarView addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBackView);
        make.left.equalTo(searchBackView).offset(3);
        make.width.height.equalTo(@20);
    }];
    
    self.searchTxf = [[UITextField alloc]init];
    [searchBarView addSubview:_searchTxf];
    _searchTxf.placeholder = @"search...";
    _searchTxf.returnKeyType = UIReturnKeySearch;
    _searchTxf.delegate = self;
    [_searchTxf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBarView);
        make.left.equalTo(icon.mas_right).offset(5);
        make.right.equalTo(searchBarView).offset(-5);
        make.height.equalTo(@20);
    }];
    [_searchTxf becomeFirstResponder];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchBtn setTitle:@"Search" forState:UIControlStateNormal];
    [searchBtn setBackgroundColor:RGBColor(255, 68, 68)];
    searchBtn.layer.cornerRadius = 3.0;
    searchBtn.titleLabel.font =[UIFont systemFontOfSize:15.0];
    [searchBackView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchBackView);
        make.width.equalTo(@70);
        make.height.equalTo(@30);
        make.right.equalTo(searchBackView).offset(-5);
    }];
    [searchBtn addTarget:self action:@selector(beginSearch) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *hotSearchBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 80)];
    hotSearchBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:hotSearchBgView];
    [hotSearchBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.navBarView.mas_bottom).offset(1);
        make.height.equalTo(@80);
    }];
    
    KKLabel *hotSearchTitleLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"Hot Search",[UIColor blackColor],[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
    }];
    [hotSearchBgView addSubview:hotSearchTitleLbl];
    [hotSearchTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(hotSearchBgView).offset(15);
        make.top.equalTo(hotSearchBgView).offset(3);
        make.width.equalTo(@100);
        make.height.equalTo(@25);
    }];
    
    self.searchScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    _searchScrollView.backgroundColor = [UIColor whiteColor];
    [hotSearchBgView addSubview:_searchScrollView];
    [_searchScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(hotSearchBgView);
        make.top.equalTo(hotSearchTitleLbl.mas_bottom);
        make.centerX.equalTo(hotSearchBgView);
        make.bottom.equalTo(hotSearchBgView.mas_bottom);
    }];
    
    

    
    UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.centerX.equalTo(self.view);
        make.top.equalTo(hotSearchBgView.mas_bottom).offset(10);
        make.bottom.equalTo(self.view);
    }];
    table.backgroundColor = [UIColor clearColor];
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.historyTable = table;
}
- (void)beginSearch
{
    DDGoodsListViewController *vc = StoryBoardViewController(@"Shop", @"DDGoodsListViewController");
    vc.vcType = DingDongGoodsControllerTypeSearch;
    vc.searchKeyword = _searchTxf.text;
    [self.navigationController pushViewController:vc animated:YES];
    
    NSString *fileName = [KKFileManager createFileWithName:@"SearchHistory"];
    NSMutableArray *ary = [NSMutableArray arrayWithContentsOfFile:fileName];
    if (!ary) {
        ary = [[NSMutableArray alloc]initWithCapacity:0];
    }
    [ary addObject:_searchTxf.text];
    BOOL success = [KKFileManager saveObject:ary withPath:fileName];
    KKLog(@"写入搜索历史成功！%d",success);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self beginSearch];
    [textField resignFirstResponder];
    return YES;
}
- (void)fetchHotSearch
{
    weak_Self(self);
    [[self.manager hotSearch]subscribeNext:^(id x) {
        weakSelf.hotSet = x;
        [weakSelf reloadHotSearchWord];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)reloadHotSearchWord
{
    [[self.searchScrollView subviews]respondsToSelector:@selector(removeFromSuperview)];
    __block CGFloat addWidth = 0;
    [self.hotSet.hotAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DDHotSearchObj *word = obj;
        NSString *wordStr = word.hot_searchword;
        
        CGFloat width = [ToolKit widthWithFont:[UIFont systemFontOfSize:13.0] height:25.0 text:wordStr]+10;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = RGBColor(237, 237, 237);
        btn.layer.cornerRadius = 3.0;
        btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn setTitle:wordStr forState:UIControlStateNormal];
        [btn setFrame:CGRectMake(10+addWidth+10*idx, 15, width, 25)];
        btn.tag = 100+idx;
        [btn addTarget:self action:@selector(gotoSearchWord:) forControlEvents:UIControlEventTouchUpInside];
        [_searchScrollView addSubview:btn];
        addWidth+=width;
    }];
    [self.searchScrollView setContentSize:CGSizeMake(10+addWidth+10*self.hotSet.hotAry.count, 0)];
}
- (void)gotoSearchWord:(UIButton *)sender
{
    [self.searchTxf resignFirstResponder];
    NSInteger index = sender.tag- 100;
    DDHotSearchObj *word = self.hotSet.hotAry[index];
    DDGoodsListViewController *vc = StoryBoardViewController(@"Shop", @"DDGoodsListViewController");
    vc.vcType = DingDongGoodsControllerTypeSearch;
    vc.searchKeyword = word.hot_searchword;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.historySearchAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44.0)];
    view.backgroundColor = [UIColor whiteColor];
    KKLabel *titleLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"History Search",[UIColor blackColor],[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
    }];
    [view addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
        make.right.equalTo(view).offset(-20);
        make.height.equalTo(@30);
    }];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = RGBColor(237, 237, 237);
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.bottom.centerX.equalTo(view);
        make.height.equalTo(@1);
    }];
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"SearchCell";
    
    DDSearchTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDSearchTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.contentLbl.text = self.historySearchAry[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchTxf resignFirstResponder];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DDGoodsListViewController *vc = StoryBoardViewController(@"Shop", @"DDGoodsListViewController");
    vc.vcType = DingDongGoodsControllerTypeSearch;
    vc.searchKeyword = self.historySearchAry[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

@implementation DDSearchTableCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.contentLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
            lbl.laText(@"",[UIColor darkGrayColor],[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
        }];
        [self.contentView addSubview:_contentLbl];
        [_contentLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(15);
            make.height.equalTo(@30);
            make.right.equalTo(self.contentView).offset(-20);
        }];
        
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = RGBColor(237, 237, 237);
        [self.contentView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.bottom.centerX.equalTo(self.contentView);
            make.height.equalTo(@1);
        }];
    }
    return self;
}
@end
